package com.ruoyi.web.cp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.cp.wechat.WeChatMsgSend;
import com.ruoyi.web.cp.wechat.WeChatUrlData;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class WinxinService {

    @SneakyThrows
    public void sendTextMessage(String appid, String msg) {
        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("@all", "text", Integer.valueOf(appid), "content", msg);
        String res = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, WeChatMsgSend.getToken(Integer.valueOf(appid), true));
        JSONObject jsonObject = JSONObject.parseObject(res);
        String errcode = jsonObject.getString("errcode");
        if (StrUtil.equals("42001", errcode)) {
            res = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, WeChatMsgSend.getToken(Integer.valueOf(appid), false));
        }
    }

    public void uploadMediaByAppAndSendMsg(String appid, String path) {
        WeChatMsgSend swx = new WeChatMsgSend();
        String token = WeChatMsgSend.getToken(Integer.parseInt(appid), true);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?type=file&access_token=" + token;
        JSONObject data = swx.uploadMediaByApp(url, path);
        if ("0".equals(data.getString("errcode"))) {
            String mediaId = data.getString("media_id");
            String params = swx.createpostdata("@all", "file", Integer.parseInt(appid), mediaId);
            HttpUtil.createPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token)
                    .body(params)
                    .execute().body();
        }
    }

    public String uploadMedia(String key, String path) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?type=file&key=" + key;
        return HttpUtil.createPost(url)
                .form("file", new File(path))
                .execute().body();
    }

    public String sendMedia(String key, String mediaId) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key;
        JSONObject body = new JSONObject();
        body.put("msgtype", "file");
        JSONObject fileBody = new JSONObject();
        fileBody.put("media_id", mediaId);
        body.put("file", fileBody);
        return HttpUtil.createPost(url)
                .body(body.toJSONString())
                .execute().body();
    }

    public void sendQlMedia(String key, String path) {
        JSONObject data = JSONObject.parseObject(uploadMedia(key, path));
        if (CollUtil.isEmpty(data)) {
            return;
        }
        String media_id = data.getString("media_id");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key;

        JSONObject params = new JSONObject();
        params.put("msgtype", "file");
        JSONObject file = new JSONObject();
        file.put("media_id", media_id);
        params.put("file", file);
        HttpUtil.createPost(url)
                .body(params.toJSONString())
                .execute().body();
    }

    public void sendQlMsg(String key, String msg) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key;
        JSONObject params = new JSONObject();
        params.put("msgtype", "text");
        JSONObject text = new JSONObject();
        text.fluentPut("content", msg);
        params.put("text", text);

        String body = HttpUtil.createPost(url)
                .body(params.toJSONString())
                .execute().body();
        log.info("{},msg:{}", key, msg);
        log.info("{},res:{}", key, body);
    }

//    public static void main(String[] args) {
//        //https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5a41eff2-8201-4fdf-aaf1-427da4ba4afb
//        String key = "c328724f-232d-486b-a88e-45a520922143";
//        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key;
//
//        JSONObject params = new JSONObject();
//        params.put("msgtype", "text");
//        params.put("safe", "1");
//        JSONObject text = new JSONObject();
//        text.fluentPut("content", "2025-10-24 16:30,印尼超,巴克伦佛,帕尔斯巴亚,62082760.1\n" +
//                "3-0|0.47|151|收：-24.370\n" +
//                "FB双进:1.75\n" +
//                "2025-10-24 17:00,乌克甲,切尔尼夫,扎波罗热米塔路,62493384.1\n" +
//                "0-3|0.49|201|收：-5.900\n" +
//                "FB双进:2.14\n" +
//                "2025-10-24 18:30,阿塞超,卡云艾夫拉克,托武兹,63185403.1\n" +
//                "3-0|0.55|201|收：-0.500\n" +
//                "FB双进:2.12\n" +
//                "2025-10-24 21:00,克亚甲,奥利简特,杜格普里耶,61464645.1\n" +
//                "0-3|0.61|201|收：4.900\n" +
//                "FB双进:2.25");
//        params.put("text", text);
//
//        System.out.println(params.toJSONString());
//        HttpUtil.createPost(url)
//                .body(params.toJSONString())
//                .execute().body();
//    }

    public static void main(String[] args) {
//        test();
        WinxinService service = new WinxinService();
        String[][] fileConfigs = {
                {"C:\\rm\\rmob-merge150.txt", "全场波胆"},
                {"C:\\rm\\rmob-merge-half150.txt", "半场波胆"}
        };
        List<String> list = new ArrayList<>();
        for (String[] config : fileConfigs) {
            list.add(config[1]);
            FileUtil.readLines(config[0], "utf-8", list);
        }
        System.out.println(list.size());
        //https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=afc29fba-c55b-44bf-8563-dec4bc7fbb51
        //https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c328724f-232d-486b-a88e-45a520922143
        service.sendQlMsg("c328724f-232d-486b-a88e-45a520922143", CollUtil.join(list, "\n"));
    }

    public static void test() {
        String corpid = "ww209d447c04b369a1";
        String corpsecret = "5J8bPGWDKUIyJA7X7zjP1EkrNr3HadVTPvLHjT2hRy0";


        String tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;

        String res = HttpUtil.get(tokenUrl);
        String accessToken = JSONObject.parseObject(res).getString("access_token");

        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        JSONObject params = new JSONObject();
        params.put("touser", "@all");
//        params.put("toparty", "PartyID1|PartyID2");
//        params.put("totag", "TagID1 | TagID2");
        params.put("msgtype", "text");
        params.put("agentid", 1);

        JSONObject text = new JSONObject();
        text.put("content", "你的快递已到，请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"https://work.weixin.qq.com\">邮件中心视频实况</a>，聪明避开排队。");
        params.put("text", text);

        params.put("safe", 1);
        params.put("enable_id_trans", 0);
        params.put("enable_duplicate_check", 0);
        params.put("duplicate_check_interval", 1800);


        String body = HttpUtil.createPost(url)
                .body(params.toJSONString())
                .execute().body();


        System.out.println(body);
    }


}
